import axios from "axios";

/**
 * baseUrl 请求基础地址
 * isDebug 是否调试，一般用于日志打印
 */
let baseUrl = process.env.VUE_APP_HTTP_BASE_URL;


axios.defaults.timeout = 15000 * 4 * 6;

// axios.defaults.timeout = 1000*60;
axios.defaults.baseURL = baseUrl;
axios.defaults.withCredentials = true;
// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    // config.data = JSON.stringify(config.data);
    // 这里的config包含每次请求的内容
    //请求携带token
    const Token = localStorage.getItem("Token");
    if (Token) {
      config.headers["Token"] = Token;
    }
    if (config.url.indexOf("/file/uploadFile") != -1 || config.url.indexOf("/file/uploadFileList") != -1 || config.url
      .indexOf("/onlineInsure/insure") != -1 ||
      config.url.indexOf("/file/uploadCaseFile") != -1

    ) {

    } else {
      config.data = JSON.stringify(config.data);
      config.headers["Content-Type"] = "application/json;charset=UTF-8";
    }
    // config.headers["Content-Type"] = "application/json;charset=UTF-8";
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  (res) => {
    // const data = res.data;
    const data = res.data;
    if (data.code === 101) {
      window.location.href = "/";
    }
    if (data.code === 102) {

      window.location.href = "/";
    }
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise}
 */

export function get(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

/**
 * 封装post请求
 * @param url
 * @param params
 * @returns {Promise}
 */

export function post(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装patch请求
 * @param url
 * @param params
 * @returns {Promise}
 */

export function patch(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, params).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

/**
 * 封装put请求
 * @param url
 * @param params
 * @returns {Promise}
 */

export function put(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, params).then(
      (response) => {
        resolve(response.data);
      },
      (err) => {
        reject(err);
      }
    );
  });
}

export function baseURL() {
  return baseUrl;
}
